/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.gtask.remote;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.ui.NotesPreferenceActivity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;


public class GTaskClient {
    private static final String TAG = GTaskClient.class.getSimpleName();

    private static final String GTASK_URL = "https://mail.google.com/tasks/";

    private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";

    private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";

    private static GTaskClient mInstance = null;

    private DefaultHttpClient mHttpClient;

    private String mGetUrl;

    private String mPostUrl;

    private long mClientVersion;//检测 API 版本，避免请求失败

    private boolean mLoggedin;//记录是否已登录 Google Tasks

    private long mLastLoginTime;//记录上次登录时间

    private int mActionId;//同步任务的 ID

    private Account mAccount;//用于存储 Google 账户信息

    private JSONArray mUpdateArray;

    private GTaskClient() {//构造函数。初始化各个变量
        mHttpClient = null;
        mGetUrl = GTASK_GET_URL;
        mPostUrl = GTASK_POST_URL;
        mClientVersion = -1;
        mLoggedin = false;
        mLastLoginTime = 0;
        mActionId = 1;
        mAccount = null;
        mUpdateArray = null;
    }

    public static synchronized GTaskClient getInstance() {//实现了单例模式，确保 GTaskClient 只会有一个全局实例。
        if (mInstance == null) {
            mInstance = new GTaskClient();
        }
        return mInstance;
    }

    public boolean login(Activity activity) {//登录 Google 任务（GTask）账户
        // we suppose that the cookie would expire after 5 minutes
        // then we need to re-login
        final long interval = 1000 * 60 * 5;// 假设 Cookie 5 分钟后会过期，需要重新登录
        if (mLastLoginTime + interval < System.currentTimeMillis()) {//距上次登录超五分钟，重新登陆
            mLoggedin = false;//标记为未登录
        }

        // need to re-login after account switch
        if (mLoggedin//若处于已登录状态，但切换账户，也需要重新登陆
                && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
                        .getSyncAccountName(activity))) {
            mLoggedin = false;
        }

        if (mLoggedin) {//若处于已登录状态，直接返回
            Log.d(TAG, "already logged in");
            return true;
        }

        mLastLoginTime = System.currentTimeMillis();
        String authToken = loginGoogleAccount(activity, false);//获取 Google 账户身份验证令牌authToken
        if (authToken == null) {
            Log.e(TAG, "login google account failed");
            return false;
        }

        // login with custom domain if necessary
        if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
                .endsWith("googlemail.com"))) {//账户后缀不是 gmail.com 或 googlemail.com
            StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
            int index = mAccount.name.indexOf('@') + 1;//需要用 自定义域名 URL 登录
            String suffix = mAccount.name.substring(index);
            url.append(suffix + "/");
            mGetUrl = url.toString() + "ig";
            mPostUrl = url.toString() + "r/ig";

            if (tryToLoginGtask(activity, authToken)) {//尝试登录
                mLoggedin = true;
            }
        }

        // try to login with google official url
        if (!mLoggedin) {//尝试用 Google 官方 URL 登录
            mGetUrl = GTASK_GET_URL;
            mPostUrl = GTASK_POST_URL;
            if (!tryToLoginGtask(activity, authToken)) {//尝试登录。
                return false;
            }
        }

        mLoggedin = true;//标记为已经成功登录
        return true;
    }

    private String loginGoogleAccount(Activity activity, boolean invalidateToken) {//获取 Google 账户的身份验证令牌（authToken）
        String authToken;
        AccountManager accountManager = AccountManager.get(activity);
        Account[] accounts = accountManager.getAccountsByType("com.google");

        if (accounts.length == 0) {//检查是否有可用的 Google 账户，若没有
            Log.e(TAG, "there is no available google account");
            return null;
        }

        String accountName = NotesPreferenceActivity.getSyncAccountName(activity);//查找匹配的 Google 账户
        Account account = null;
        for (Account a : accounts) {
            if (a.name.equals(accountName)) {
                account = a;
                break;
            }
        }
        if (account != null) {//到匹配的 Google 账户
            mAccount = account;//将其存入 mAccount 变量，表示该账户已被选中
        } else {//否则返回null，打印错误
            Log.e(TAG, "unable to get an account with the same name in the settings");
            return null;
        }

        // get the token now
        AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
                "goanna_mobile", null, activity, null, null);//通过 AccountManager 获取身份验证令牌
        try {
            Bundle authTokenBundle = accountManagerFuture.getResult();
            authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
            if (invalidateToken) {
                accountManager.invalidateAuthToken("com.google", authToken);
                loginGoogleAccount(activity, false);
            }
        } catch (Exception e) {
            Log.e(TAG, "get auth token failed");
            authToken = null;
        }

        return authToken;//返回获取到的身份验证令牌authToken
    }

    private boolean tryToLoginGtask(Activity activity, String authToken) {//尝试使用 authToken 登录 Google 任务（GTask）API
        if (!loginGtask(authToken)) {//尝试使用 authToken 登录 GTask,若失败
            // maybe the auth token is out of date, now let's invalidate the
            // token and try again
            authToken = loginGoogleAccount(activity, true);//获取新的 authToke
            if (authToken == null) {
                Log.e(TAG, "login google account failed");
                return false;
            }

            if (!loginGtask(authToken)) {//使用新的 authToken 再次尝试登录
                Log.e(TAG, "login gtask failed");
                return false;
            }
        }
        return true;
    }

    private boolean loginGtask(String authToken) {//尝试登录的具体实现
        int timeoutConnection = 10000;//配置 HTTP 客户端
        int timeoutSocket = 15000;
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        mHttpClient = new DefaultHttpClient(httpParameters);
        BasicCookieStore localBasicCookieStore = new BasicCookieStore();//设置 Cookie 存储
        mHttpClient.setCookieStore(localBasicCookieStore);
        HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);

        // login gtask
        try {
            String loginUrl = mGetUrl + "?auth=" + authToken;//发送 HTTP GET 请求进行登录
            HttpGet httpGet = new HttpGet(loginUrl);
            HttpResponse response = null;
            response = mHttpClient.execute(httpGet);

            // get the cookie now
            List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();//获取身份验证 Cookie
            boolean hasAuthCookie = false;
            for (Cookie cookie : cookies) {
                if (cookie.getName().contains("GTL")) {
                    hasAuthCookie = true;
                }
            }
            if (!hasAuthCookie) {
                Log.w(TAG, "it seems that there is no auth cookie");
            }

            // get the client version
            String resString = getResponseContent(response.getEntity());//解析服务器返回的客户端版本
            String jsBegin = "_setup(";
            String jsEnd = ")}</script>";
            int begin = resString.indexOf(jsBegin);
            int end = resString.lastIndexOf(jsEnd);
            String jsString = null;
            if (begin != -1 && end != -1 && begin < end) {
                jsString = resString.substring(begin + jsBegin.length(), end);
            }
            JSONObject js = new JSONObject(jsString);
            mClientVersion = js.getLong("v");
        } catch (JSONException e) {//错误处理
            Log.e(TAG, e.toString());
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            // simply catch all exceptions
            Log.e(TAG, "httpget gtask_url failed");
            return false;
        }

        return true;
    }

    private int getActionId() {
        return mActionId++;
    }//生成一个唯一的 Action ID,每次加一

    private HttpPost createHttpPost() {//创建一个 HTTP POST 请求，用于向Google Tasks 服务器发送任务更新、创建、删除等请求
        HttpPost httpPost = new HttpPost(mPostUrl);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        httpPost.setHeader("AT", "1");
        return httpPost;
    }

    private String getResponseContent(HttpEntity entity) throws IOException {//从 HTTP 响应的实体中读取内容
        String contentEncoding = null;
        if (entity.getContentEncoding() != null) {// 获取响应实体的编码格式
            contentEncoding = entity.getContentEncoding().getValue();
            Log.d(TAG, "encoding: " + contentEncoding);
        }

        InputStream input = entity.getContent();//// 获取实体内容的输入流
        if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {// 如果响应是 GZIP 格式
            input = new GZIPInputStream(entity.getContent());//使用 GZIPInputStream 解压
        } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {//// 如果响应是 Deflate 格式
            Inflater inflater = new Inflater(true);
            input = new InflaterInputStream(entity.getContent(), inflater);//使用 InflaterInputStream 解压
        }

        try {//// 使用输入流读取响应内容
            InputStreamReader isr = new InputStreamReader(input);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();

            while (true) {// 循环读取每行数据并构建字符串
                String buff = br.readLine();
                if (buff == null) {
                    return sb.toString();// 返回读取的完整内容
                }
                sb = sb.append(buff);// 将每行数据拼接起来
            }
        } finally {
            input.close();
        }
    }

    private JSONObject postRequest(JSONObject js) throws NetworkFailureException {//通过 HTTP POST 请求向服务器发送数据
        if (!mLoggedin) {//检查登录状态,若没登录
            Log.e(TAG, "please login first");
            throw new ActionFailureException("not logged in");//抛出异常，提示用户先登录
        }

        HttpPost httpPost = createHttpPost();//创建 HTTP POST 请求
        try {
            LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
            list.add(new BasicNameValuePair("r", js.toString()));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(entity);

            // execute the post
            HttpResponse response = mHttpClient.execute(httpPost);//发送请求
            String jsString = getResponseContent(response.getEntity());//从响应中获取内容，并将其转换为字符串
            return new JSONObject(jsString);//将获取到的响应字符串 (jsString) 转换为 JSONObject

        } catch (ClientProtocolException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new NetworkFailureException("postRequest failed");
        } catch (IOException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new NetworkFailureException("postRequest failed");
        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("unable to convert response content to jsonobject");
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("error occurs when posting request");
        }
    }

    public void createTask(Task task) throws NetworkFailureException {//创建一个新的任务
        commitUpdate();//提交更新
        try {
            JSONObject jsPost = new JSONObject();//准备请求数据
            JSONArray actionList = new JSONArray();

            // action_list
            actionList.put(task.getCreateAction(getActionId()));
            jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);

            // client_version
            jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);//添加客户端版本信息

            // post
            JSONObject jsResponse = postRequest(jsPost);//发送 POST 请求
            JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(//解析服务器响应
                    GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
            task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));

        } catch (JSONException e) {//异常处理
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("create task: handing jsonobject failed");
        }
    }

    public void createTaskList(TaskList tasklist) throws NetworkFailureException {//创建新的任务列表
        commitUpdate();//提交更新
        try {
            JSONObject jsPost = new JSONObject();//准备请求数据,jsPost用于存放请求数据
            JSONArray actionList = new JSONArray();//actionList用于存储操作列表

            // action_list
            actionList.put(tasklist.getCreateAction(getActionId()));//生成一个任务列表创建的操作对象,将任务列表创建的操作添加到该列表中
            jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);

            // client version
            jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);//添加客户端版本信息

            // post
            JSONObject jsResponse = postRequest(jsPost);//发送 POST 请求
            JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
                    GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
            tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));

        } catch (JSONException e) {//错误处理
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("create tasklist: handing jsonobject failed");
        }
    }

    public void commitUpdate() throws NetworkFailureException {//提交更新的任务操作
        if (mUpdateArray != null) {//检查是否有待更新的操作，若有
            try {
                JSONObject jsPost = new JSONObject();//创建一个jsPost用于存储请求的数据

                // action_list
                jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);//放人待提交的更新操作列表

                // client_version
                jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);//将当前客户端版本添加到jspost中

                postRequest(jsPost);//发送请求
                mUpdateArray = null;//清空更新操作集合
            } catch (JSONException e) {//错误处理
                Log.e(TAG, e.toString());
                e.printStackTrace();
                throw new ActionFailureException("commit update: handing jsonobject failed");
            }
        }
    }

    public void addUpdateNode(Node node) throws NetworkFailureException {//将一个新的更新操作节点添加到待更新的操作列表中
        if (node != null) {//若传入的节点不为空
            // too many update items may result in an error
            // set max to 10 items
            if (mUpdateArray != null && mUpdateArray.length() > 10) {//如果 mUpdateArray 已经存在并且其长度超过 10
                commitUpdate();//提交更新
            }

            if (mUpdateArray == null)//若之前没有任何待更新的操作
                mUpdateArray = new JSONArray();//初始化一个新的 JSONArray 来存储待提交的更新操作
            mUpdateArray.put(node.getUpdateAction(getActionId()));//添加新的更新操作
        }
    }

    public void moveTask(Task task, TaskList preParent, TaskList curParent)//将一个任务从一个任务列表（preParent）移动到另一个任务列表（curParent）
            throws NetworkFailureException {
        commitUpdate();//提交更新操作
        try {
            JSONObject jsPost = new JSONObject();//jsPost用于表示移动任务的请求。
            JSONArray actionList = new JSONArray();//actionList用于存放任务移动的具体操作
            JSONObject action = new JSONObject();//action用于描述当前任务的移动操作

            // action_list
            action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
                    GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);//GTASK_JSON_ACTION_TYPE设置为 "move"，表示这是一个移动任务的操作
            action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());//获取一个新的操作 ID
            action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());//设置任务的 ID
            if (preParent == curParent && task.getPriorSibling() != null) {//如果任务是在同一个任务列表中移动并且有上一个兄弟任务
                // put prioring_sibing_id only if moving within the tasklist and
                // it is not the first one
                action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());//则设置该字段
            }
            action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());//设置源任务列表的 ID
            action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());//设置目标任务列表的父任务 ID
            if (preParent != curParent) {//如果任务是从一个任务列表移动到另一个任务列表
                // put the dest_list only if moving between tasklists
                action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());//设置目标任务列表的 ID
            }
            actionList.put(action);//将前面创建的 action 对象添加到 actionList中
            jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);//将 actionList（操作列表）添加到最终的 jsPost中

            // client_version
            jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);//将客户端的版本信息（mClientVersion）添加到 jsPost中

            postRequest(jsPost);//提交请求

        } catch (JSONException e) {//错误处理
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("move task: handing jsonobject failed");
        }
    }

    public void deleteNode(Node node) throws NetworkFailureException {//删除一个任务节点（Node）
        commitUpdate();//提交更新
        try {
            JSONObject jsPost = new JSONObject();
            JSONArray actionList = new JSONArray();

            // action_list
            node.setDeleted(true);//将 node 对象的删除状态标记为 true，表示该节点已被删除
            actionList.put(node.getUpdateAction(getActionId()));//创建一个包含该节点删除操作的 action 对象
            jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);

            // client_version
            jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);//将当前客户端版本（mClientVersion）添加到 jsPost 中

            postRequest(jsPost);//将请求对象 jsPost 发送给服务器，执行删除操作
            mUpdateArray = null;//表示更新操作已经完成并提交
        } catch (JSONException e) {//错误处理
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("delete node: handing jsonobject failed");
        }
    }

    public JSONArray getTaskLists() throws NetworkFailureException {//获取所有任务列表
        if (!mLoggedin) {//检查是否登录
            Log.e(TAG, "please login first");
            throw new ActionFailureException("not logged in");
        }

        try {
            HttpGet httpGet = new HttpGet(mGetUrl);//执行 HTTP GET 请求
            HttpResponse response = null;
            response = mHttpClient.execute(httpGet);

            // get the task list
            String resString = getResponseContent(response.getEntity());//获取响应内容
            String jsBegin = "_setup(";//提取 JSON 数据
            String jsEnd = ")}</script>";
            int begin = resString.indexOf(jsBegin);
            int end = resString.lastIndexOf(jsEnd);
            String jsString = null;
            if (begin != -1 && end != -1 && begin < end) {
                jsString = resString.substring(begin + jsBegin.length(), end);
            }
            JSONObject js = new JSONObject(jsString);//解析 JSON 数据
            return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
        } catch (ClientProtocolException e) {//异常处理
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new NetworkFailureException("gettasklists: httpget failed");
        } catch (IOException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new NetworkFailureException("gettasklists: httpget failed");
        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("get task lists: handing jasonobject failed");
        }
    }

    public JSONArray getTaskList(String listGid) throws NetworkFailureException {//获取指定任务列表（ListGid）
        commitUpdate();//提交更新
        try {
            JSONObject jsPost = new JSONObject();//构建请求数据
            JSONArray actionList = new JSONArray();
            JSONObject action = new JSONObject();

            // action_list
            action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
                    GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
            action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
            action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
            action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
            actionList.put(action);
            jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);

            // client_version
            jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);

            JSONObject jsResponse = postRequest(jsPost);//发送请求
            return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);//获取响应
        } catch (JSONException e) {//异常处理
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("get task list: handing jsonobject failed");
        }
    }

    public Account getSyncAccount() {
        return mAccount;
    }//返回 mAccount (当前的google账户)对象

    public void resetUpdateArray() {
        mUpdateArray = null;
    }//清空 mUpdateArray(用来存储需要发送到服务器的操作或更新列表)
}
